import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import member from "@src/store/member";
import base from "@src/store/base";
import memberPayBehavior from "@src/common/memberPayBehavior";
import {
  parseCategoryRights,
  parseRechargeAwardRule,
} from "@src/common/memberCardUtils";
import {
  getCategoryAvailable,
  getOpenCardInfo,
  openMemberCard,
  updateToNewCard,
  checkWxCardState
} from "@src/api/member";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior, memberPayBehavior],
  storeBindings: [{
    store: member,
    fields: ['isMember', 'memberName', 'categoryName', 'categoryId', 'cardOrder'],
    actions: ['getBaseInfo', 'syncWxCard']
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor', 'indexPageScene']
  }],
  data: {
    billDetailModal: false,
    wxCardState: {
      hasGet: false,
      hasActive: false,
    },
    openCardInfo: null,
    openCategoryId: null,
    category: null,
    cardList: [],
    cardListTemp: [],
    cardPrivateCount: null,
  },
  methods: {
    onLoad(options) {
      let { categoryId } = options;
      if (categoryId) {
        this.setData({ openCategoryId: Number(categoryId) })
      }
    },
    onLogin() {
      this.fetchData();
    },
    fetchData: function () {
      let data = {
        categoryId: this.data.openCategoryId
      }
      getCategoryAvailable(data).then(res => {
        let availableData = res.data;
        if (!availableData) {
          availableData = [];
        }
        let cardList = [];
        let cardListTemp = [];
        let category = null;
        let openCategoryId = this.data.openCategoryId
        console.info("cardOrder: {}", this.data.cardOrder)
        for (let card of availableData) {
          if (card.category.cardOrder <= this.data.cardOrder) {
            continue;
          }
          if (card.category.id === openCategoryId) {
            this.resetCurCard(card);
            category = card.category;

          }
          cardListTemp.push(card);
          cardList.push(card.category);
        }
        if (category == null && cardList.length > 0) {
          category = cardList[0];
          openCategoryId = category.id;
        }
        this.setData({ cardList: cardList, cardListTemp: cardListTemp, openCategoryId, category, toWhichCard: 'card-' + openCategoryId })
      })
      getOpenCardInfo(data).then(res => {
        if (res.code === 0) {
          this.setData({ openCardInfo: res.data });
        }
      })
      checkWxCardState().then(res => {
        if (res.code === 0) {
          this.setData({ wxCardState: { hasActive: res.data.hasActive, hasGet: res.data.hasGet } })
        }
      })
    },
    resetCurCard(card) {
      console.log('我改的card', card)
      let category = card.category;
      //let privileges = card.privileges;
      let rechargeAward = card.rechargeAward;
      let categoryRights = parseCategoryRights(category, rechargeAward).concat(parseRechargeAwardRule(rechargeAward));
      this.setData({
        cardPrivateCount: categoryRights.length
      })
    },
    handleViewBillDetail() {
      this.setData({ billDetailModal: !this.data.billDetailModal })
    },
    handleCloseBillDetail() {
      this.setData({ billDetailModal: false })
    },
    handleToDetail() {
      router.back();
    },
    handleOpenCard() {
      let resultData = {}
      if (this.data.wxCardState.hasGet && !this.data.wxCardState.hasActive) {
        resultData = this.selectComponent("#person-info").validItemArr();
        if (!resultData) {
          return;
        }
      }
      wx.showLoading({ title: "开卡中...", mark: true});
      let data = {
        categoryId: this.data.openCategoryId,
        intoWay: this.data.indexPageScene.receiveWay,
        channel: 2,
        data: resultData,
        scene: this.data.indexPageScene.scene
      };
      let reqApi;
      if (this.data.isMember) {
        reqApi = updateToNewCard
      } else {
        reqApi = openMemberCard
      }
      console.log('reqApi', reqApi)
      reqApi(data).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          this.setData({ openCardData: res.data })
          if (res.data.needPay) {
            let payData = {
              orderNo: res.data.orderCode,
              payChannels: ["wx"],
              hasDiscount: false
            }
            this.toMemberPay(payData).then(res => {
              this.syncStateFunc();
            }).catch(res => {
              console.info('支付error', res)
            });
          } else {
            this.syncStateFunc();
          }
        } else {
          wx.showToast({ title: res.msg, icon: "none", duration: 3000 });
        }
      }).catch(res => {
        wx.hideLoading();
      })
    },
    syncStateFunc() {
      // 刷新会员数据
      if (!this.data.wxCardState.hasGet) {
        this.syncWxCard();
      } else {
        wx.showModal({
          title: "温馨提示",
          content: "开通成功",
          showCancel: false,
          confirmText: "回首页",
          success(res) {
            if (res.confirm) {
              router.push({ name: 'index' })
            }
          }
        });
      }
      this.getBaseInfo();
    },
    handleStop() {
      return true;
    },
    handleChange(e) {
      let category = e.currentTarget.dataset.category;
      let cardListTemp = this.data.cardListTemp;
      console.log('cardListTemp', cardListTemp)
      cardListTemp.forEach(item => {
        if (item.category) {
          if (item.category.id == category.id) {
            this.resetCurCard(item)
          }
        }
      })
      this.setData({ category, openCategoryId: category.id, toWhichCard: 'card-' + category.id })
    }
  }
})
